from django.core.paginator import Paginator
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render
from apps.project.models import Projects_model,Projects_users_model
from apps.users.models import Users_model
from django.core.cache import cache
from apps.config.serializers import Menu_serializer
# Create your views here.
# 项目表页面
def project_view(request):
    menu_list = cache.get('menu_list')
    menu_obj = Menu_serializer(menu_list, many=True)
    return render(request, 'project/list.html', {'data1': menu_obj.data})

# 项目表数据
def project_list(request):
    pro_list = Projects_model.objects.filter()
    count = Projects_model.objects.count()
    data_list=[]
    for i in pro_list:
        dict = {}
        dict['id'] = i.id
        dict['pro_name'] = i.pro_name
        dict['paper_code'] = i.pro_contract.paper_code
        dict['paper_manager'] = i.pro_contract.paper_manager.username
        dict['audit_customer'] = i.pro_contract.paper_customer.cus_audited_object
        dict['pro_number'] = i.pro_number
        dict['sign_one'] = i.sign_one.username
        dict['sign_two'] = i.sign_two.username
        dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
        dict['user_user'] = list(i.projects_users_model.user_user.all().values_list('user_code',flat=True))  # 项目成员
        dict['user_Independence'] = i.projects_users_model.user_Independence
        dict['print_amount'] = i.print_amount
        dict['now_status'] = i.pro_status
        dict['remark'] = i.remark_describe
        data_list.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(data_list, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    return JsonResponse({'code': 0, 'msg': '成功！', 'count': count, 'data': res})

# 添加页面
def project_insert_view(request):
    return render(request, 'project/insert.html')

@transaction.atomic
def project_insert(request):
    # 判断是否有权限id
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '300101' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    pro_name = request.POST.get('pro_name')    # 项目名称
    pro_contract = request.POST.get('pro_contract') # 关联协议的ID
    sign_one = request.POST.get('sign_one') # 签字人一
    sign_two = request.POST.get('sign_two') # 签字人二
    print_number = request.POST.get('print_number') # 打印张数
    remark_describe = request.POST.get('remark_describe') # 备注
    try:
        Projects_model.objects.create(pro_name=pro_name, pro_contract_id=pro_contract, sign_one_id=sign_one,
                                      sign_two_id =sign_two,sign_one_opinion_id=1,sign_two_opinion_id=1,
                                      print_amount=print_number, remark_describe=remark_describe
                                      )
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 203, 'msg': '服务器发生错误，请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': '添加成功！'})

# 详情页
def project_detail_view(request):
    return render(request,'project/detail.html')

# 添加项目成员,这里逻辑是处于拟稿阶段的时候，可以随意修改项目人员
@transaction.atomic
def project_insertuser(request):
    pro_id = request.POST.get('id')     # 项目
    independence = request.POST.get('independence') #是否需要签署独立性申明
    users = request.POST.get('user_code')
    new_users = list(str(users).split(','))
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    for i in new_users:
        if i == ',':
            new_users.remove(i)
    try:
        # 这里需要判断
        user_list = Projects_users_model.objects.filter(user_project_id=pro_id)
        if user_list is None:
            obj = Projects_users_model.objects.create(user_Independence=independence, user_project_id=pro_id)
            user_obj_list = Users_model.objects.filter(user_code__in=new_users)
            obj.user_user.add(*user_obj_list)
            obj.save()
        else:             # 不为空，则为更改数据
            obj=Projects_users_model.objects.get(user_project_id=pro_id)
            obj.user_Independence=independence
            obj.user_user.clear()
            user_obj_list = Users_model.objects.filter(user_code__in=new_users)
            obj.user_user.add(*user_obj_list)
            obj.save()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1) # 可以回滚到指定的保存点
        return JsonResponse({'code': 203, 'msg': '未知错误！请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': '添加成功！'})